package com.ujiuye.interceptor;

import com.ujiuye.context.BaseContext;
import com.ujiuye.exceptions.MyException;
import com.ujiuye.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shiminghui
 * @date 2024/8/19 19:59
 * @description: TODO
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        log.info("jwt校验执行了");
        // 从Session、Token等中获取用户登录状态
        String token = request.getHeader("Authorization");
        log.info("token的值{}", token);
        if (token == null) {
            // 用户未登录，重定向到登录页面或返回未授权响应
            response.setStatus(401); // 或者设置状态码和错误信息
            return false; // 返回false表示拦截器处理完成，不继续执行后续的Controller
        }

        //jwt校验
        Claims claims = null;
        try {
            claims = jwtUtils.parseJwt(token);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
        if (claims == null) {
            response.setStatus(401);
            return false;
        }

        String id = claims.getId();
        String subject = claims.getSubject();
        String companyId = (String) claims.get("companyId");
        String companyName = (String) claims.get("companyName");
        //将id传入线程局部变量中
        BaseContext.setCurrentId(id);
        log.info("放行");
        return true; // 返回true表示继续执行后续的Controller
    }


    // postHandle和afterCompletion方法根据需要实现
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可以在这里处理视图渲染之前的逻辑
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 可以在这里处理整个请求完成之后的逻辑，如资源清理
    }
}
